<?php

/* $Revision: 1.6 $ */

$PageSecurity=17;

include('includes/session.inc');

$title = _('Quyền hạn truy cập');
include('includes/header.inc');

if (isset($_GET['SelectedRole'])){
	$SelectedRole = $_GET['SelectedRole'];
} elseif (isset($_POST['SelectedRole'])){
	$SelectedRole = $_POST['SelectedRole'];
}
echo '<center>';
if (isset($_POST['submit']) || isset($_GET['remove']) || isset($_GET['add']) ) {

	//initialise no input errors assumed initially before we test
	$InputError = 0;

	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */
	//first off validate inputs sensible
	if (isset($_POST['SecRoleName']) && strlen($_POST['SecRoleName'])<4){
		$InputError = 1;
		prnMsg(_('Chiều dài mô tả quyền hạn phải ít nhất 4 ký tự.'),'error');
	}
	
	// if $_POST['SecRoleName'] then it is a modifications on a SecRole
	// else it is either an add or remove of a page token 
	unset($sql);
	if (isset($_POST['SecRoleName']) ){ // Update or Add Security Headings
		if(isset($SelectedRole)) { // Update Security Heading
			$sql = "UPDATE securityroles SET secrolename = N'".DB_escape_string($_POST['SecRoleName'])."' 
					WHERE secroleid = ".$SelectedRole;
			$ErrMsg = _('Cập nhật mô tả quyền hạng lỗi vì');
			$ResMsg = _('Quyền hạn đã cập nhật.');
		} else { // Add Security Heading
			$sql = "INSERT INTO securityroles (secrolename) VALUES (N'".DB_escape_string($_POST['SecRoleName'])."')";
			$ErrMsg = _('Thêm quyền hạn mới đã lỗi vì ');
			$ResMsg = _('Quyền hạn đã tạo.');
		}
		unset($_POST['SecRoleName']);
		unset($SelectedRole);
	} elseif (isset($SelectedRole) ) {
		$PageTokenId = $_GET['PageToken'];
		if( isset($_GET['add']) ) { // updating Security Groups add a page token
			$sql = "INSERT INTO securitygroups ( 
					secroleid, tokenid 
					) VALUES (
					".$SelectedRole.", 
					".$PageTokenId."
					)";
			$ErrMsg = _('The addition of the page group access failed because');
			$ResMsg = _('Chức năng đã cho phép truy cập.');
		} elseif ( isset($_GET['remove']) ) { // updating Security Groups remove a page token
			$sql = "DELETE FROM securitygroups 
					WHERE secroleid = ".$SelectedRole."
					AND tokenid = ".$PageTokenId;
			$ErrMsg = _('The removal of this page-group access failed because');
			$ResMsg = _('Đã từ chối truy cập chức năng.');
		}
		unset($_GET['add']);
		unset($_GET['remove']);
		unset($_GET['PageToken']);
	}
	// Need to exec the query
	if (isset($sql) && $InputError != 1 ) {
		$result = DB_query($sql,$db,$ErrMsg);
		if( $result ) {
			prnMsg( $ResMsg,'success');
		}
	}
} elseif (isset($_GET['delete'])) { 
	//the Security heading wants to be deleted but some checks need to be performed fist
	// PREVENT DELETES IF DEPENDENT RECORDS IN 'www_users'
	$sql= "SELECT COUNT(*) as c FROM www_users WHERE fullaccess=" . $_GET['SelectedRole'];
	$result = DB_query($sql,$db);
	$myrow = DB_fetch_array($result);
	if ($myrow['c']>0) {
		prnMsg( _('Cannot delete this role because user accounts are setup using it'),'warn');
		echo '<br>' . _('There are') . ' ' . $myrow['c'] . ' ' . _('user accounts that have this security role setting') . '</font>';
	} else {
		$sql="DELETE FROM securitygroups WHERE secroleid=" . $_GET['SelectedRole'];
		$result = DB_query($sql,$db);
		$sql="DELETE FROM securityroles WHERE secroleid=" . $_GET['SelectedRole'];
		$result = DB_query($sql,$db);
		prnMsg( $_GET['SecRoleName'] . ' ' . _('đã xóa.') . '!','success');

	} //end if account group used in GL accounts
	unset($SelectedRole);
	unset($_GET['SecRoleName']);
}

if (!isset($SelectedRole)) {

/* If its the first time the page has been displayed with no parameters then none of the above are true and the list of Users will be displayed with links to delete or edit each. These will call the same page again and allow update/input or deletion of the records*/

	$result = _single('api/securityroles')->GetSecurityRolesList($_SESSION['UserID'], $_SESSION['Password']);
	
	echo '<br/>';
	echo '<table border=1  class="pretty-table">';
	echo "<tr><th>" . _('Quyền hạn') . "</th><th>" . _(' ') . "</th><th>" . _(' ') . "</th></tr>";
	
	$k=0; //row colour counter

	foreach($result as $key=>$value){
		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k=1;
		}

		/*The SecurityHeadings array is defined in config.php */

		printf("<td>%s</td>
			<td><a href=\"%s&SelectedRole=%s\">" . _('Cập nhật') . "</a></td>
			<td><a href=\"%s&SelectedRole=%s&delete=1&SecRoleName=%s\">" . _('Xóa') . "</a></td>
			</tr>",
			$value,
			$_SERVER['PHP_SELF']  . "?" . SID,
			$key,
			$_SERVER['PHP_SELF'] . "?" . SID,
			$key,
			urlencode($value));

	} //END WHILE LIST LOOP
	echo '</table><br>';
	
} //end of ifs and buts!


if (isset($SelectedRole)) {
	echo "<br /><div class='centre'><a href='" . $_SERVER['PHP_SELF'] ."?" . SID . "'>" . _('Quay lại danh sách quyền hạn') . '</a></div>';
}

if (isset($SelectedRole)) {
	//editing an existing role

	$result = _single('api/securityroles')->GetSecroleById($SelectedRole, $_SESSION['UserID'], $_SESSION['Password']);
	if(empty($result)){
		prnMsg( _('Quyền hạn bạn chọn không tồn tài.'),'warn');
	}else{
		$_POST['SelectedRole'] = $result['secroleid'];
		$_POST['SecRoleName'] = $result['secrolename'];
	}
}
echo '<br>';
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . "?" . SID . ">";
if( isset($_POST['SelectedRole'])) {
	echo "<input type=hidden name='SelectedRole' VALUE='" . $_POST['SelectedRole'] . "'>";
}
echo '<table>';
if (!isset($_POST['SecRoleName'])) {
	$_POST['SecRoleName']='';
}
if (isset($SelectedRole)) {
	$lblSubmit = _('Cập nhật');
}else{
	$lblSubmit = _('Thêm mới');
}
echo '<tr><td>' . _('Quyền hạn') . ":</td>
	<td><input type='text' name='SecRoleName' size=40 maxlength=40 VALUE='" . $_POST['SecRoleName'] . "'></tr>";
echo "</table><br />
	<div class='centre'><input type='Submit' name='submit' value='" . $lblSubmit . "'></div></form>";

if (isset($SelectedRole)) {
	
	$Result = _single('api/securitytokens')->GetSecurityTokensList($_SESSION['UserID'], $_SESSION['Password']);
	
	/*Make an array of the used tokens */
	$UsedResult = _single('api/securitygroups')->GetTokensBySecroleId($SelectedRole, $_SESSION['UserID'], $_SESSION['Password']);
	$TokensUsed = array();
	$i=0;
	while ($myrow=DB_fetch_array($UsedResult)){
		$TokensUsed[$i] =$myrow['tokenid'];
		$i++;
	} 
	
	echo '<br /><table class="pretty-table"><tr>';
	
	if (DB_has_rows($Result)>0 ) {
		echo "<th colspan=3><div class='centre'>"._('Chức năng đã cho phép')."</div></th>";
		echo "<th colspan=3><div class='centre'>"._('Chức năng trong hệ thống')."</div></th>";
	}
	echo '</tr>';
	
	$k=0; //row colour counter
	while($AvailRow = DB_fetch_array($Result)) {
				
		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k=1;
		}
		
		if (in_array($AvailRow['tokenid'],$TokensUsed)){
			printf("<td>%s</td><td>%s</td>
				<td><a href=\"%s&SelectedRole=%s&remove=1&PageToken=%s\">" . _('Từ chối') . "</a></td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>",
				$AvailRow['tokenid'],
				$AvailRow['tokenname'],
				$_SERVER['PHP_SELF']  . "?" . SID,
				$SelectedRole,
				$AvailRow['tokenid'] 
				);
		} else {
			printf("<td>&nbsp;</td>
				<td>&nbsp;</td>
				<td>&nbsp;</td>
				<td>%s</td>
				<td>%s</td>
				<td><a href=\"%s&SelectedRole=%s&add=1&PageToken=%s\">" . _('Cho phép') . "</a></td>",
				$AvailRow['tokenid'],
				$AvailRow['tokenname'],
				$_SERVER['PHP_SELF']  . "?" . SID,
				$SelectedRole,
				$AvailRow['tokenid'] 
				);
		}	
		echo '</tr>';
	}
	echo '</table>';
}
echo '</center>';
include('includes/footer.inc');

?>